{% extends "base.html" %}
{% block content %}
<h2>任务列表</h2>
<div class="mb-3 d-flex align-items-center">
  <input type="text" id="task-search" placeholder="搜索任务ID/类型/状态" class="form-control" style="width:200px;display:inline-block;">
  <button id="task-search-btn" class="btn btn-primary btn-sm ms-2">查询</button>
</div>
<table class="table table-bordered table-striped table-hover align-middle" style="table-layout:fixed;word-break:break-all;">
  <thead>
    <tr>
      <th style="width:30%;">任务ID</th>
      <th style="width:10%;">类型</th>
      <th style="width:10%;">状态</th>
      <th style="width:20%;">创建时间</th>
      <th style="width:30%;">操作</th>
    </tr>
  </thead>
  <tbody id="task-table"></tbody>
</table>
<div class="d-flex justify-content-end align-items-center" style="margin-top:-10px;">
  <div class="task-pagination-bar d-flex align-items-center flex-wrap gap-2">
    <span>每页</span>
    <select id="task-page-size" class="form-select form-select-sm mx-1" style="width:80px;display:inline-block;">
      <option value="10">10</option>
      <option value="20" selected>20</option>
      <option value="50">50</option>
      <option value="100">100</option>
    </select>
    <span>条，共 <span id="task-total-info">0</span> 条</span>
    <ul class="pagination flex-wrap mb-0 ms-3" id="task-pagination" style="margin-bottom:0 !important;"></ul>
  </div>
</div>
<style>
.table td, .table th { vertical-align: middle; }
.task-pagination-bar {
  background: #fff;
  border-radius: 8px;
  padding: 8px 16px 8px 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  font-size: 0.98rem;
}
.download-btn {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}
</style>
<script>
let taskPage = 1, taskPageSize = 20, taskQuery = '';

function formatDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function loadTasks() {
  fetch(`/api/tasks?q=${encodeURIComponent(taskQuery)}&page=${taskPage}&page_size=${taskPageSize}`)
    .then(r=>r.json()).then(res=>{
      let html = res.data.map(t=>{
        let downloadLinks = '';
        if (t.download_files && t.download_files.length > 0) {
          downloadLinks = t.download_files.map(f => 
            `<a href="${f.download_url}" class="btn btn-success btn-sm ms-1 download-btn" target="_blank" title="${f.file_name}">下载: ${f.file_name.length > 10 ? f.file_name.substring(0, 10) + '...' : f.file_name}</a>`
          ).join('');
        }
        return `<tr>
          <td>${t.id}</td>
          <td>${t.type}</td>
          <td>${t.status}</td>
          <td>${formatDate(t.created_at)}</td>
          <td><a href="/task-detail/${t.id}">详情</a>${downloadLinks}</td>
        </tr>`;
      }).join('');
      document.getElementById('task-table').innerHTML = html;
      
      // 分页
      let totalPages = Math.max(1, Math.ceil(res.total / res.page_size));
      let pagHtml = '';
      let showPages = 7;
      let start = Math.max(1, taskPage - Math.floor(showPages/2));
      let end = Math.min(totalPages, start + showPages - 1);
      if (end - start < showPages - 1) start = Math.max(1, end - showPages + 1);
      if (start > 1) pagHtml += `<li class="page-item"><a class="page-link" href="#">1</a></li>` + (start>2?'<li class="page-item disabled"><span class="page-link">…</span></li>':'');
      for(let i=start;i<=end;i++){
        pagHtml += `<li class="page-item${i===taskPage?' active':''}"><a class="page-link" href="#">${i}</a></li>`;
      }
      if (end < totalPages) pagHtml += (end<totalPages-1?'<li class="page-item disabled"><span class="page-link">…</span></li>':'')+`<li class="page-item"><a class="page-link" href="#">${totalPages}</a></li>`;
      document.getElementById('task-pagination').innerHTML = pagHtml;
      document.querySelectorAll('#task-pagination .page-link').forEach((el)=>{
        if (!el.parentElement.classList.contains('disabled')) {
          el.onclick = (e)=>{
            let num = parseInt(el.textContent);
            if (!isNaN(num)) { taskPage=num; loadTasks(); }
          };
        }
      });
      
      // 总数信息
      document.getElementById('task-total-info').textContent = res.total;
    });
}

document.getElementById('task-search-btn').onclick = ()=>{
  taskQuery = document.getElementById('task-search').value.trim();
  taskPage = 1;
  loadTasks();
};

document.getElementById('task-page-size').onchange = function() {
  taskPageSize = parseInt(this.value);
  taskPage = 1;
  loadTasks();
};

loadTasks();
</script>
{% endblock %} 